package com.vue.service.impl;

import com.google.common.util.concurrent.RateLimiter;
import com.vue.config.DeepSeekConfig;
import com.vue.entity.po.ChatRequest;
import com.vue.entity.vo.ChatResponse;
import com.vue.service.DeepSeekService;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.HttpEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.ArrayList;
import java.util.List;

/**
 * @author: wrj
 * @since: 2025/2/12 09:26
 * @description:
 */

@Slf4j
@Service
@AllArgsConstructor
public class DeepSeekServiceImpl implements DeepSeekService {

    private DeepSeekConfig config;
    private final RestTemplate restTemplate = new RestTemplate();

    // 使用Guava RateLimiter添加限流
    private final RateLimiter rateLimiter = RateLimiter.create(10.0); // 每秒10次

    @Override
    public String send(String message) {

        if (!rateLimiter.tryAcquire()) {
            throw new RuntimeException("先稍等啊，本大厨快忙不过来了");
        }

        try {
            // 构建请求体
            ChatRequest request = new ChatRequest();
            List<ChatRequest.Message> messages = new ArrayList<>();
            messages.add(new ChatRequest.Message("system", "你是一命私人生活助理，精通各种生活常识，但是回答尽量精简，控制字数"));
            messages.add(new ChatRequest.Message("user", message));
            request.setMessages(messages);

            // 发送请求
            HttpEntity<ChatRequest> entity = new HttpEntity<>(request, config.createHeaders());
            ResponseEntity<ChatResponse> response = restTemplate.postForEntity(
                    config.API_URL,
                    entity,
                    ChatResponse.class
            );

            // 处理响应
            if (response.getStatusCode().is2xxSuccessful() &&
                    !response.getBody().getChoices().isEmpty()) {
                return response.getBody().getChoices().get(0).getMessage().getContent();
            }
            return "我这脑袋瓜子不够用了";
        } catch (Exception e) {
            // 记录日志
            return "大厨有点忙，稍坐哈";
        }
    }
}
